<template>
  <div id="app">
    <Header></Header>
    <Goods
      v-for="item in list"
      :key="item.id"
      :goodsName="item.goods_name"
      :goodsPrice="item.goods_price"
      :imgUrl="item.goods_img"
      :state="item.goods_state"
      :id="item.id"
      :num_g="item.goods_count"
      @stateChange="getNewState"
    >
      <Counter
        :num_c="item.goods_count"
        @amount-change="getNewAmount(item, $event)"
      ></Counter>
    </Goods>
    <Footer
      :state="fullState"
      @isFull="getState"
      :amount="totalAmount"
      :totalPrice="totalPrice"
    ></Footer>
  </div>
</template>

<script>
import Header from "./components/Header.vue";
import Goods from "./components/Goods.vue";
import Footer from "./components/Footer.vue";
import axios from "axios";
import bus from "./EventBus.js";
import Counter from "./components/Counter.vue";
export default {
  name: "App",
  data() {
    return {
      list: [],
    };
  },
  components: {
    Header,
    Goods,
    Counter,
    Footer,
  },
  methods: {
    async initCartList() {
      const { data: res } = await axios.get("https://www.escook.cn/api/cart");
      if (res.status === 200) {
        this.list = res.list;
        console.log(res.list);
      }
    },
    getNewState(e) {
      this.list.some((item) => {
        if (item.id === e.id) {
          item.goods_state = e.value;
          return true;
        }
      });
    },
    getState(val) {
      this.list.forEach((item) => {
        item.goods_state = val;
      });
    },
    getNewAmount(item, e) {
      item.goods_count = e;
    },
  },
  created() {
    this.initCartList();
    console.log('========')
  },
  computed: {
    fullState() {
      return this.list.every((item) => item.goods_state);
    },
    totalAmount() {
      return this.list
        .filter((item) => item.goods_state)
        .reduce((amount, item) => (amount += item.goods_count), 0);
    },
    totalPrice() {
      return this.list
        .filter((item) => item.goods_state)
        .reduce(
          (totalPrice, item) =>
            (totalPrice += item.goods_count * item.goods_price),
          0
        );
    },
  },
};
</script>

<style lang="less">
</style>
